//
//  SelectPickerView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/20.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

enum selectStyle {
    case identiStyle
    case timeStyle
    case dateStyle
}


class SelectPickerView: UIView {
    var nameArr:Array<Any> = []
    var selectHeight: Int = 0 //选择控件高度
    var selectTop: CGFloat? //选择控件距离顶部距离
    var style: selectStyle?
    var dataSource: SlecterProcotol?
    var title:String = ""
    var selectContent:AnyObject?
    var selectDateArr:Array<Int> = [] //选择的日期
    
    lazy var backView: UIView =  {
        let top = CGFloat(kSCREEN_HEIGHT) - CGFloat(selectHeight)
        
        let view = UIView(frame: CGRect(x: 0, y: top, width: kSCREEN_WIDTH, height:CGFloat(selectHeight)))
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
    }()
    
    lazy var cancelBtn: UIView = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        btn.setTitle(kText("取消"), for: UIControlState.normal)
        btn.addTarget(self, action: #selector(cancelBtnAction), for: UIControlEvents.touchUpInside)
        if ThemeManager.default.currentThemeMode() == .night {
            btn.setTitleColor(UIColor(hexStr: "#616979"), for: UIControlState.normal)
        }else {
            btn.setTitleColor(KCommonTextColor, for: UIControlState.normal)
        }
        return btn
    }()
    
    lazy var sureBtn: UIView = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        btn.setTitle(kText("确认"), for: UIControlState.normal)
        btn.addTarget(self, action: #selector(sureBtnAction), for: UIControlEvents.touchUpInside)
        btn.setTitleColor(kThemeColor, for: UIControlState.normal)
        return btn
    }()
    
    lazy var titleLabel: UILabel = {
        let label = BaseLabel(style: .oneStyle)
        label.text = ""
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()
    
    lazy var selecterView: SelectPickerView =  {
        let view =  (self.creatSelectStyle(style: style!, title: title, dataArr: nameArr, dataSource: dataSource!) as! SelectPickerView)
        view.themeBackground = ThemeManager.ThemeColorKeys.background
      return view
    }()
    
    init(style:selectStyle, title:String, selectStr:AnyObject?, dataArr:Array<Any> ,dataSource:SlecterProcotol) {
        super.init(frame:CGRect.zero)
        nameArr = dataArr
        self.style = style
        self.dataSource = dataSource
        selectHeight = 209
        selectTop = 65
        if style == .dateStyle {
            selectHeight = 352
        }
        if title.ch_length != 0 {
            titleLabel.text = title
        }
        if ((selectStr as? String) != nil) {
            self.selectContent = selectStr != nil ? selectStr as! String as AnyObject : "" as AnyObject
        }
        if ((selectStr as? Array<Any>) != nil) {
            self.selectContent = selectStr
        }
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func pickerShow() -> Void {
        let window = UIApplication.shared.keyWindow
        window?.addSubview(self)
        self.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalToSuperview()
        }
        let tap = UITapGestureRecognizer(target: self, action: #selector(giveUpFirstRespond(sender:)))
        tap.numberOfTapsRequired = 1
        tap.cancelsTouchesInView = false
        self.addGestureRecognizer(tap)
        
       self.addSubview(backView)
//        backView.snp.makeConstraints { (make) in
//            make.bottom.equalToSuperview().offset(-209)
//            make.left.right.equalToSuperview()
//            make.height.equalTo(209)
//        }
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(20)
            make.centerX.equalToSuperview()
        }
        
       backView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(8)
            make.centerY.equalTo(titleLabel)
            make.width.equalTo(50)
            make.height.equalTo(32)
        }
        
        backView.addSubview(sureBtn)
        sureBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.centerY.equalTo(titleLabel)
            make.width.equalTo(33)
            make.height.equalTo(32)
        }
        
       backView.addSubview(selecterView)
       selecterView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(selectTop!)
            make.bottom.equalToSuperview()
        }
        
        self.trans(view: backView)
       
    }
    func trans(view:UIView) -> Void {
        let animation = CABasicAnimation(keyPath: "position")
        animation.fromValue = NSValue(cgPoint: CGPoint(x: view.layer.position.x, y:view.layer.position.y+CGFloat(selectHeight)) )
        animation.toValue = NSValue(cgPoint: view.layer.position )
        animation.duration = 0.3
        animation.isRemovedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        view.layer.add(animation, forKey: "position")
    }
    
    func closeTrans(view:UIView) -> Void {
        let animation = CABasicAnimation(keyPath: "position")
        animation.fromValue = NSValue(cgPoint: view.layer.position )
        animation.toValue = NSValue(cgPoint: CGPoint(x: view.layer.position.x, y:view.layer.position.y+CGFloat(selectHeight)) )
        animation.duration = 0.3
        animation.isRemovedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        view.layer.add(animation, forKey: "position")
        self.removeFromSuperview()
    }
    
    @objc func cancelBtnAction() -> Void {
        self.closeTrans(view: backView)
    }
    
    @objc func sureBtnAction() -> Void {
        if dataSource != nil {
            if style == .dateStyle {
                for cell in (selecterView as! SelectDatePickerView).cellArr {
                    if cell.selectStateBool {
                        if cell.tag - KCellTag == 0 {
                            selectDateArr.append(7)
                        }else {
                            selectDateArr.append(cell.tag-KCellTag)
                        }
                    }
                }
                dataSource?.selectData(selecter: selectDateArr as AnyObject)
            }else {
                
                dataSource?.selectData(selecter: selecterView.selectContent as AnyObject)
            }
        }
        self.closeTrans(view: backView)
    }
    
    func creatSelectStyle(style:selectStyle,title:String, dataArr:Array<Any>, dataSource: SlecterProcotol) -> AnyObject? {
        var selector: SelectPickerView?
        switch style {
        case .identiStyle:
            selector =  SelectIdentyPickView(style:style, title: title,selectStr:self.selectContent as AnyObject, dataArr: dataArr, dataSource: dataSource)
            break
        
        case .timeStyle:
            selector =  SelectTimePickerView(style:style, title: title,selectStr:self.selectContent as AnyObject, dataArr: dataArr, dataSource: dataSource)
            break
        
        case .dateStyle:
            selector =  SelectDatePickerView(style:style, title: title,selectStr:self.selectContent as AnyObject, dataArr: dataArr, dataSource: dataSource)
            break
        }
        return selector!
    }
    
    
    @objc func giveUpFirstRespond(sender:UITapGestureRecognizer) -> Void {
        if (sender.state == UIGestureRecognizerState.ended) {
            let location = sender.location(in: self)
            if !backView.point(inside: backView.convert(location, from: self), with: nil) {
                self.closeTrans(view: backView)
            }
        }
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
